import config from '../config/index.js'
import utils from '../utils/util.js'
const app = getApp();

function _login(temps = {}, currnt_app) { //登录事件
  postRequest('/toolkit/login/loginpost', {
    username: temps.username,
    password: temps.password,
  }).then(res => {
    if (res.code == 0) {
      let token = res.data.token;
      let userInfo = res.data;
      wx.setStorageSync('token', token);
      wx.setStorageSync('userInfo', userInfo);
      currnt_app.globalData.userInfo = userInfo;
      wx.switchTab({
        url: '/pages/index/index',
      })
    }
    wx.showToast({
      title: res.message,
      icon: res.code == 0 ? 'success' : 'none'
    })
  })
}

function isLogin() { //判断是否登陆
  var token = app.globalData.userInfo ? app.globalData.userInfo.token : null;
  var storageToken = wx.getStorageSync('token') ? wx.getStorageSync('token') : null;
  if (!storageToken) {
    wx.redirectTo({
      url: '/pages/login/index',
    })
  }
}

function wxPromisefy(obj = {}) {
  return new Promise((resolve, reject) => {
    obj.header = obj.header ? obj.header : {}
    obj.header = Object.assign(obj.header, {
      'token': wx.getStorageSync('token')
    })
    obj.success = function(res) {
      if (res.data.code == 3) {
        //console.log('token为空')
        isLogin();
        return
      }
      resolve(res.data)
    }
    wx.request(obj);
  })
}

function postRequest(url, data = {}, header = {}) {
  return wxPromisefy({
    url: config.domain + url,
    method: 'POST',
    data: data,
  })
}

function getRequest(url, data = {}, header = {}) {
  return wxPromisefy({
    url: config.domain + url,
    method: 'POST',
    data: data
  })
}

module.exports = {
  postRequest: postRequest,
  getRequest: getRequest,
  login: _login,
  isLogin
}